package mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by 10188 on 2018/3/31.
 */
public class MqttClientTest {

    private static final String broker = "tcp://127.0.0.1:1883";

    private static final String clientId = "client";
    void connect() {
        MqttClient client;
        try {
            client = new MqttClient(broker, clientId, new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);
            options.setConnectionTimeout(10000);
            options.setKeepAliveInterval(10000);
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable throwable) {
                    Calendar calendar = Calendar.getInstance();
                    Date date = calendar.getTime();
                    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                    System.out.println(sdf.format(date)+"----连接已断开");
                }

                @Override
                public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                    System.out.println("收到来信" + new String(mqttMessage.getPayload()));

                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                    System.out.println("发送完成");
                }
            });
            client.connect(options);
            send(client);
            client.subscribe("inner");
        } catch (MqttException e) {
            e.printStackTrace();
        }

    }


    void send (MqttClient client) throws MqttException {
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setRetained(true);
        mqttMessage.setQos(2);
        mqttMessage.setPayload("test发送的消息".getBytes());
        MqttTopic topic = client.getTopic("hello");
        topic.publish(mqttMessage);
    }

    public static void main(String[] args) {
            new MqttClientTest().connect();
    }
}
